package pack1;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class CommonControllers {

	@Autowired
	private UserDAO userdao;
	
	@Autowired
	private LoginDetDAO logindetdao;
	
	@RequestMapping(value="/NewUserRegForm")
	public ModelAndView getNewUserRegForm()
	{
		ModelAndView mav = new ModelAndView("userForm");
		return mav;
	}
	
	@RequestMapping(value="/userRegForm")
	public ModelAndView create(@ModelAttribute("NewUser")User user, BindingResult result, SessionStatus status)
	{
		
		System.out.println("**************");
	/*	validator.validate(contact, result);
		if (result.hasErrors()) 
		{				
			return "newContact";
		}*/
 
		System.out.println(" Dob : "+user.getDob() +"  Email : "+ user.getEmail());
		System.out.println(" Gender : "+user.getGender() +"  Password : "+ user.getPassword());
		System.out.println("==============");
		
		UserDet userdet = new UserDet();
		LoginDet logindet= new LoginDet();
		
		userdet.setFname(user.getFname()); 
		userdet.setLname(user.getLname()); 
		userdet.setAddress(user.getAddress());
		
		SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
		try {
			Date userDob = formatter.parse(user.getDob());
			userdet.setDob(userDob); 
		} catch (ParseException e) {
			e.printStackTrace();
		}
		userdet.setBgroup(user.getBgroup()); 
		userdet.setGender(user.getGender());
		userdet.setContactno(user.getContactno());
		
		logindet.setEmail(user.getEmail());
		logindet.setPass(user.getPassword());
		
		int id=userdao.getSeq();
		if(id!=0) {
		userdet.setId(id);
		logindet.setId(id);
		userdao.save(userdet);
		logindetdao.save(logindet);	
		
		ModelAndView mav = new ModelAndView("success");
		status.setComplete();
		return mav;
		}
		else {
			ModelAndView mav = new ModelAndView("Failure");
			status.setComplete();
			return mav;
		}
		
	}
}
